package org.nf.web.view;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.nf.web.servlet.ServletApi;
import org.nf.web.servlet.View;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhu
 * @date 2024-05-20
 */
public class ForwardView implements View {

    private final String url;

    private Map<String , Object> map = new HashMap<>();

    public ForwardView(String url) {
        this.url = url;
    }

    public void addObject(String key, Object value) {
        map.put(key, value);
    }

    @Override
    public void render(ServletApi servletApi) throws ServletException, IOException {
        HttpServletRequest request = servletApi.req();
        HttpServletResponse response = servletApi.resp();
        // 将map集合的数据保存到请求作用域
        map.forEach(request::setAttribute);
        // 执行转发
        request.getRequestDispatcher(url).forward(request, response);
    }
}
